<?php

use Biz\model\activity\ActivityAwardDelivery;
use Doraemon\tools\Log;
use Doraemon\model\Phone as PhoneModel;
use hhz\constant\basic\UserExtendPhoneScene;

/**
 * 活动 用户收件人信息 或则 用户联系信息
 */
class ReceiveRecordAction extends ActionPlugin
{

    const USER_LEVEL = self::LEVEL_NOTHING;

    private $activityId = 0;

    public function main()
    {
        $data = $this->getData();

        $res = ActivityAwardDelivery::insert($data);

        if ($res->rowCount() > 0) {
            $response = $this->getReturnRes(true);
        } else {
            $response = $this->getReturnRes(false);
        }
        $this->setSuccess($response['data'], $response['code'], $response['message']);
    }

    private function getData()
    {
        $activityId = $this->getRequest()->getPost('activity_id', 0);
        $phone = trim($this->getRequest()->getPost('phone', ''));
        $name = trim($this->getRequest()->getPost('name', ''));
        $areaCode = trim($this->getRequest()->getPost('area_code', ''));
        $address = trim($this->getRequest()->getPost('address', ''));
        $award = $this->getRequest()->getPost('award_id', null);

        $this->activityId = $activityId;
        $phone = $phone ? str_replace(["\r\n", "\r", "\n", " "], "", $phone) : '';

        if (is_null($award)) {
            $award = $this->getRandAward();
        }
        $deliveryAddress = ($areaCode || $address) ? ($areaCode . ActivityAwardDelivery::ADDRESS_SEPARATOR . $address) : '';

        $activityName = ActivityAwardDelivery::ACTIVITY_MAP[$activityId] ?? '';
        if (empty($activityId) || !$activityName) {
            throw new \Exception('不存在的活动');
        }
        $encryptPhoneId = '';
        switch ($activityId) {
            case ActivityAwardDelivery::ACTIVITY_DONGPENG_COLLECT:
                if (empty($phone)) {
                    throw new \Exception('请填写手机号');
                }
                if (empty($name)) {
                    throw new \Exception('请填写姓名');
                }
                $hasData = ActivityAwardDelivery::count(['activity_id' => $activityId, 'activity_encrypt_phone' => $this->encryptPhone($phone)]);
                if ($hasData) {
                    throw new \Exception('您已报名');
                }
                if ($phone) {
                    //不同的活动，加密手机号使用的场景值不一样，新加活动，请选添加或则确认相关场景值
                    $encryptPhoneId = PhoneModel::addExtendPhone($phone,UserExtendPhoneScene::DONGPENG_ACTIVITY_SUBMIT_PHONE);
                    if (!$encryptPhoneId) {
                        Log::error('添加手机号失败', [$phone, $encryptPhoneId]);
                        throw new \Exception('活动太火爆了，请稍后再试');
                    }
                }
                break;
        }


        $data = [
            'activity_id' => $activityId,
            'uid' => $this->uid,
            'award' => $award,
            'name' => $name,
            'encrypt_phone_id' => $encryptPhoneId,
            'activity_encrypt_phone' => $this->encryptPhone($phone),
            'delivery_address' => $deliveryAddress,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        return $data;
    }

    private function getReturnRes($success = true)
    {
        $response = [
            'code' => self::API_CODE_SUCCES,
            'data' => null,
            'message' => '',
        ];
        switch ($this->activityId) {
            case ActivityAwardDelivery::ACTIVITY_DONGPENG_COLLECT:
                if ($success) {
                    $response['message'] = '报名成功';
                } else {
                    $response['message'] = '报名失败';
                    $response['code'] = self::API_CODE_ERROR;
                }
                break;
        }
        return $response;


    }

    private function encryptPhone($phone)
    {
        return $phone ? md5(ActivityAwardDelivery::PHONE_SECRETS . $phone) : '';
    }

    private function getRandAward()
    {
        $award = $this->activityId . ceil(microtime(true) * 1000) . mt_rand(0, 999);
        $award = str_pad($award, 20, '0', STR_PAD_RIGHT);
        $award = substr($award, 0, 20);
        $hasAward = ActivityAwardDelivery::count(['activity_id' => $this->activityId, 'uid' => $this->uid, 'award' => $award]);
        if (!$hasAward) {
            return $award;
        } else {
            return $this->getRandAward();
        }
    }

}